package com.msk.web.controller.system;

import com.msk.common.constant.Constants;
import com.msk.common.constant.UserConstants;
import com.msk.common.core.domain.R;
import com.msk.common.utils.MessageUtils;
import com.msk.common.utils.StringUtils;
import com.msk.framework.web.service.SysApiRegisterService;
import com.msk.message.service.ISmsClientService;
import com.msk.sys.domain.User;
import com.msk.sys.service.SysParamService;
import com.msk.sys.service.SystemService;
import com.msk.sys.utils.DictMskUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * @Description 系统注册及验证码信息接口
 * @Author zlf
 * @Date 2023/5/11 11:27
 */
@Api(tags = "接口信息管理")
@RestController
@RequestMapping("/api/mp")
public class SysApiInfoController {

    @Autowired
    private SystemService systemService;

    @Autowired
    private ISmsClientService smsClientService;

    @Autowired
    private SysApiRegisterService registerService;

    @Autowired
    private SysParamService sysParamService;

    /**
     * 发送验证码
     * @param params
     * @return
     */
    @PostMapping("/sendAliCode")
    @ApiOperation("发送验证码")
    @ResponseBody
    public R<?> sendAliCode(@RequestBody Map<String, Object> params) {
        String phone = StringUtils.getString(params.get("phone"));
        //1、注册 2、登录 3、修改/忘记密码
        String sendType = StringUtils.getString(params.get("sendType"));
        if (StringUtils.isBlank(phone)) {
            return R.appFail(2001, "请求参数#phone不能为空");
        }
        if (StringUtils.isBlank(sendType)) {
            return R.appFail(2001, "请求参数#sendType不能为空");
        }

        String msg = "";
        //验证码开关0:开，1关
        String validateCodeSwitch = DictMskUtils.getDictLabel("1", "validate_code_switch", "0");
        if ("1".equals(validateCodeSwitch)) {
            return R.appFail(2001, "手机验证码已关闭");
        }
        boolean mobileExist = systemService.checkMobileExist(phone);
        String type = "";
        if ("1".equals(sendType)) {
            type = DictMskUtils.getDictValue("注册模板", "message_template", "SMS_276327423");
            if (mobileExist) {
                return R.appFail(2002, "该手机号已存在");
            }
        } else if ("2".equals(sendType)) {
            type = DictMskUtils.getDictValue("登录模板", "message_template", "SMS_276347200");
        } else if ("3".equals(sendType)) {
            type = DictMskUtils.getDictValue("修改/忘记密码模板", "message_template", "SMS_276512260");
        }
        if (StringUtils.isEmpty(type)) {
            return R.appFail(2002, "获取模板信息失败");
        }
        if ("2".equals(sendType) || "3".equals(sendType)) {
            if (!mobileExist) {
                return R.appFail(2002, "该手机号不存在");
            }
        }
        Map<String, Object> map = smsClientService.setAliPhoneCodeCache(phone, type);
        String flag = map.get("flag").toString();
        //验证码已发送
        if ("1".equalsIgnoreCase(flag)) {
            msg = "验证码已发送";
            return R.appOk(msg);
        } else if ("2".equalsIgnoreCase(flag)) {
            msg = "验证码已发送，请勿重复操作";
        } else {
            msg = "验证码发送失败";
        }
        return R.appFail(2002, msg);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/registerUser")
    @ApiOperation("用户注册")
    @ResponseBody
    public R<?> registerUser(@RequestBody User user) {
        R<?> result;
        try {
            String mobile = user.getMobile();
            String password = user.getPassword();
            String validateCode = user.getValidateCode();
            if (StringUtils.isAnyEmpty(mobile, password, validateCode)) {
                return R.appFail(2001, "参数缺失");
            }
            if (mobile.length() != UserConstants.PHONE_MIN_LENGTH) {
                return R.appFail(2001, "手机号范围错误");
            }
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH_NEW) {
                return R.appFail(2001, "密码长度不符合规范");
            }
            boolean mobileExist = systemService.checkMobileExist(mobile);
            if (mobileExist) {
                return R.appFail(2002, "该手机号已存在");
            }
            String validateCodeSwitch = DictMskUtils.getDictLabel("1", "validate_code_switch", "0");
            if ("1".equals(validateCodeSwitch)) {
                if (!"9999".equals(validateCode)) {
                    return R.appFail(2002, MessageUtils.message("user.jcaptcha.error"));
                }
            } else {
                String phoneCodeCache = smsClientService.getPhoneCodeCache(mobile);
                if (!validateCode.equals(phoneCodeCache)) {
                    return R.appFail(2002, MessageUtils.message("user.jcaptcha.error"));
                }
            }
            String userIdentity = user.getUserIdentity();
            if (!"1".equals(userIdentity) && !"2".equals(userIdentity) && !"3".equals(userIdentity)) {
                return R.appFail(2001, "身份类型错误");
            }
            result = registerService.userRegister(user);
            if (result.getCode() == Constants.SUCCESS_APP) {
                return R.appOk(result.getData(), "注册成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = R.appFail(2000, "注册失败");
        }
        return result;
    }

    /**
     * 描述: 注册协议
     * @author yangjy
     * @date 2023/7/13 18:18
     * @param
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation("注册协议")
    @PostMapping("/registrationAgreement")
    public R<?> registrationAgreement() {
        List<Map<String, Object>> sysParams = sysParamService.aboutUsAndRegistration();
        String registration = null;
        for (Map<String, Object> par : sysParams) {
            String registrationAgreement = String.valueOf(par.get("registrationAgreement"));
            try {
                registration = URLDecoder.decode(registrationAgreement, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            par.put("registrationAgreement", registration);
        }
        return R.appOk(sysParams);
    }

    /**
     * 忘记密码
     * @param user
     * @return
     */
    @PostMapping("/forgetPassword")
    @ApiOperation("忘记密码")
    @ResponseBody
    public R<?> forgetPassword(@RequestBody User user) {
        R<?> result;
        try {
            String mobile = user.getMobile();
            String password = user.getPassword();
            String validateCode = user.getValidateCode();
            String userIdentity = user.getUserIdentity();
            if (StringUtils.isAnyEmpty(mobile, password, validateCode, userIdentity)) {
                return R.appFail(2001, "参数缺失");
            }
            if (mobile.length() != UserConstants.PHONE_MIN_LENGTH) {
                return R.appFail(2001, "手机号范围错误");
            }
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH_NEW) {
                return R.appFail(2001, "密码长度不符合规范");
            }
            if (!"1".equals(userIdentity) && !"2".equals(userIdentity) && !"3".equals(userIdentity)) {
                return R.appFail(2001, "身份类型错误");
            }
            User userInfo = systemService.getByMobile(mobile, userIdentity);
            if (StringUtils.isNull(userInfo)) {
                return R.appFail(2002, "该手机号不存在");
            }
            //验证码开关0:开，1关
            String validateCodeSwitch = DictMskUtils.getDictLabel("1", "validate_code_switch", "0");
            if ("1".equals(validateCodeSwitch)) {
                if (!"9999".equals(validateCode)) {
                    return R.appFail(2002, MessageUtils.message("user.jcaptcha.error"));
                }
            } else {
                String phoneCodeCache = smsClientService.getPhoneCodeCache(mobile);
                if (!validateCode.equals(phoneCodeCache)) {
                    return R.appFail(2002, MessageUtils.message("user.jcaptcha.error"));
                }
            }
            int rows = systemService.updatePasswordById(userInfo.getId(), password);
            if (rows > 0) {
                result = R.appOk("修改成功");
            } else {
                result = R.appFail(2002, "修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = R.appFail(2000, "修改失败");
        }
        return result;
    }

    /**
     * 刷新字典缓存
     * @param param
     * @return
     */
    @PostMapping("/refreshDictInfo")
    @ApiOperation("刷新字典缓存")
    @ResponseBody
    public R<?> forgetPassword(@RequestBody Map<String, String> param) {
        R<?> result;
        try {
            String type = null;
            if (param != null && param.containsKey("type")) {
                type = param.get("type");
            }
            DictMskUtils.clearDictList(type);
            DictMskUtils.initNotExistDictList(type);
            result = R.appOk("刷新成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = R.appFail(2000, "刷新失败");
        }
        return result;
    }
}
